/**
* 描述：我的信息
*/
<style lang="scss" scoped>
  .user-center-content{
    width: 600px;
    padding-top: 50px;
    margin-left: 80px;
  }
  .user-center-content1{
    width: 500px;
    padding-top: 50px;
    margin-left: 150px;
  }
  .avatar-uploader .el-upload {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #8c939d;
    font-size: 28px;
    color: #8c939d;
    width: 108px;
    height: 108px;
    line-height: 108px;
    text-align: center;
  }
  .avatar {
    width: 108px;
    height: 108px;
    display: block;
  }
</style>
<template>
  <div class="content">
    <Tabs ref="tabs">
      <TabPane label="个人信息">
        <div class="user-center-content">
          <Form ref="infoForm" :model="infoForm" :rules="infoRule" :label-width="180" class="main-add-1 formNoRadius">
            <FormItem label="个人头像：">
              <el-upload
                style="float: left;"
                name="image"
                class="avatar-uploader logo-uploader"
                action="/api/pub/image"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :on-error="handleAvatarError">
                <img v-if="infoForm.avatar" :src="`/api/pub/image/${infoForm.avatar}`" alt="头像" width="98" height="98" style="display: block;">
                <img src="/static/images/web/userCenter/userGirl.png"  class="touxiang" v-show="!infoForm.avatar && infoForm.sex===2">
                <img src="/static/images/web/userCenter/userBoy.png"  class="touxiang" v-show="!infoForm.avatar && infoForm.sex===1">
                <i class="el-icon-plus"></i>
              </el-upload>
              <span style="float: left;color: #999;margin-left:10px;">*点击图片可重新上传 <br>*上传图片尺寸为100*100px最佳，不可大于100k</span>
              <div class="clear"></div>
            </FormItem>
            <!--<FormItem label="帐户名：" prop="oldPassword">-->
              <!--<i-input v-model="infoForm.username" :maxlength="20"  placeholder="帐户名"></i-input>-->
            <!--</FormItem>-->
            <FormItem label="用户真实姓名：" prop="realName">
              <i-input v-model="infoForm.realName" :maxlength="20" placeholder="用户真实姓名"></i-input>
            </FormItem>
            <FormItem label="性别：" prop="sex" :required="true">
              <Select v-model="infoForm.sex" placeholder="性别：" >
                <template>
                  <i-option v-for="item in sexList" :value="item.value" :key="item.value">{{item.label}}</i-option>
                </template>
              </Select>
            </FormItem>
            <FormItem label="工作职务：" prop="job">
              <i-input v-model="infoForm.job" :maxlength="100" placeholder="工作职务"></i-input>
            </FormItem>
            <FormItem label="生日：" prop="birth">
              <Date-picker type="date" placement="top-end" placeholder="生日" class="date"
                           :value="infoForm.birth" format="yyyy-MM-dd"
                           @on-change="infoForm.birth=$event" :editable="false"></Date-picker>
            </FormItem>
            <FormItem style="text-align: center">
              <Button type="ghost" @click="infoReset()" style="margin-right: 30px;background-color: #f7f7f7">重置</Button>
              <Button type="primary" :loading="formLoading" @click="infoSubmit('infoForm')">提交修改</Button>
            </FormItem>
            <div class="clear"></div>
          </Form>
        </div>
      </TabPane>
      <TabPane label="修改密码">
        <div class="user-center-content">
          <Form ref="passwordForm" :model="passwordForm" :rules="pasRule" :label-width="150" class="main-add-1 formNoRadius">
            <FormItem label="原始密码：" prop="oldPassword">
              <i-input type="password" v-model="passwordForm.oldPassword" :maxlength="18" placeholder="原始密码"></i-input>
            </FormItem>
            <FormItem label="新密码：" prop="newPassword">
              <i-input type="password" v-model="passwordForm.newPassword" :maxlength="18" placeholder="密码6-20位，必须同时含有数字、字母"></i-input>
            </FormItem>
            <FormItem label="再次输入密码：" prop="confirmNewPassword">
              <i-input type="password" v-model="passwordForm.confirmNewPassword" :maxlength="18" placeholder="再次输入密码"></i-input>
            </FormItem>
            <FormItem style="text-align: center">
              <Button type="ghost" @click="pwdReset()" style="margin-right: 30px;background-color: #f7f7f7">重置</Button>
              <Button type="primary" :loading="formLoading" @click="pwdSubmit('passwordForm')">提交修改</Button>
            </FormItem>
          </Form>
        </div>
      </TabPane>
      <TabPane label="修改手机">
        <div class="user-center-content1">
          <Form ref="phoneForm" :model="phoneForm" :rules="phoneRule" :label-width="150" class="main-add-1 formNoRadius">
            <FormItem label="用户新手机：" prop="phone">
              <i-input v-model="phoneForm.phone" :maxlength="11"  placeholder="用户新手机"></i-input>
            </FormItem>
            <FormItem label="图片验证：" class="yanzheng">
                <i-input type="text" placeholder="请输入图片验证" v-model="captcha" style="width:220px;float: left"/>
                <a style="text-align: center;margin-top: 18px;float: left;width:auto;float: left;margin-left: -4px;" @click="rndNum()"> 点击刷新</a>
                <img style="width:170px;float: right;margin-left:0;" :src="`/api/pub/captcha.jpg?randKey=${code}`">
                <div class="clear"></div>
            </FormItem>
            <FormItem label="验证码：" prop="smsCode" class="shouji">
                <i-input v-model="phoneForm.smsCode" :maxlength="6"  placeholder="请使用原手机号接收" style="width:260px;float: left"></i-input>
                <Button type="primary" :loading="phoneFunLoading" @click="sendSmsCode" style="width: 170px;padding:10px 0;border-radius: 0;float: right">
                  <span v-if="!phoneFunLoading">发送验证码</span>
                  <span v-else>{{countDown}}后重新发送</span>
                </Button>
                <div class="clear"></div>
            </FormItem>
            <FormItem>
              <Button type="primary" :loading="formLoading" @click="changePhone('phoneForm')" style="padding:10px 50px;">提交</Button>
            </FormItem>
          </Form>
        </div>
      </TabPane>
    </Tabs>
  </div>
</template>
<script>
  import { changePassword, updateProfile, changePhone } from '@/service/company/myAccount/myAccountMService';
  import md5 from 'js-md5';
  import { mapState, mapMutations, mapActions } from 'vuex';
  import { sendSmsCode } from '@/service/web/login/loginService';
  export default {
    computed: {
      ...mapState([
        'companyUserInfo'
      ])
    },
    async created () {
      if (!this.companyUserInfo.realName) await this.getCompanyUserInfo();
      this.infoForm = Object.assign({}, this.companyUserInfo);
    },
    data () {
      return {
        code: '',
        captcha: '',
        infoForm: {}, // 基本信息Form
        infoRule: {}, // 基本信息Form验证规则
        sexList: [
          {value: 1, label: '男'},
          {value: 2, label: '女'}
        ],
        formLoading: false, // 表单提交loading
        passwordForm: {}, // 修改密码Form
        pasRule: {
          oldPassword: [
            {required: true, message: '原始密码不能为空', trigger: 'blur change'}
          ],
          newPassword: [
            {required: true, message: '新密码不能为空', trigger: 'blur change'},
            {pattern: '^(?![0-9]+$)(?![a-zA-Z]+$)[,.#%’+*-:;^_`0-9A-Za-z]{6,20}$', message: '密码6-20位，必须同时含有数字、字母', trigger: 'blur change'}
          ],
          confirmNewPassword: [
            {required: true, message: '请再次输入密码！', trigger: 'blur change'},
            {validator: (rule, val, callback) => {
                if (this.passwordForm.newPassword !== val) {
                  callback('两次输入的密码不一致');
                } else {
                  callback();
                }
              }}
          ]
        }, // 修改密码Form验证规则
        accept: ['image/jpeg', 'image/png'], // 上传图片验证格式
        phoneForm: {}, // 修改手机Form
        phoneRule: {
          phone: [
            {required: true, message: '手机号不能为空', trigger: 'blur'},
            {pattern: '^(1[3,4,5,6,7,8])\\d{9}$', message: '手机号格式不对', trigger: 'blur change'}
          ]
        },  // 修改手机Form验证规则
        countDown: 60, // 倒计时初始值
        countDownIntervalid: null, // 倒计时定时器
        phoneFunLoading: false // 验证码loading
      };
    },
    mounted () {
    },
    methods: {
      ...mapMutations([
        'COMPANY_USER_INFO'
      ]),
      ...mapActions([
        'getCompanyUserInfo'
      ]),
      // 生成随机数 5位 即 随机生成图片
      rndNum () {
        let xxx = Math.random().toString(36).substr(2);
        let aa = xxx.slice(0, 5);
        this.code = aa;
      },
      // 个人信息提交
      infoSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (!valid) return;
          this.$confirm('确定修改个人信息吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            this.formLoading = true;
            let userInfoData = Object.assign({}, this.infoForm);
            userInfoData.birth = this._hyTool.DateFormat(new Date(userInfoData.birth), 'yyyy-MM-dd hh:mm:ss');
            await updateProfile(userInfoData);
            this.formLoading = false;
            this.$Notice.success({title: '修改成功'});
            this.getCompanyUserInfo();
          }).catch(() => {
            this.formLoading = false;
          });
        });
      },
      // 个人信息重置 (信息不全)
      infoReset () {
        this.infoForm = Object.assign({}, this.companyUserInfo);
      },
      // 密码重置
      pwdReset () {
        this.passwordForm = {
          oldPassword: '',
          newPassword: '',
          confirmNewPassword: ''
        };
      },
      // 修改密码提交
      pwdSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (!valid) return;
          this.$confirm('确定修改密码吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            let para = {
              oldPassword: md5(this.passwordForm.oldPassword),
              newPassword: this.passwordForm.newPassword
            };
            this.formLoading = true;
            await changePassword(para);
            this.$Notice.success({title: '修改成功'});
            this._hyTool.removeStore('companyLoginInfo');
            this.$router.push('/company/login');
          }).catch(() => {
            this.formLoading = false;
          });
        });
      },
      // 图片上传失败
      handleAvatarError () {
        this.$Notice.error({title: '上传失败，请稍后再试'});
      },
      // 图片上传之前
      beforeAvatarUpload (file) {
        const isJPG = this.accept.indexOf(file.type) > -1;
        const isLt2M = file.size / 1024 < 100;
        if (!isJPG) {
          this.$Notice.warning({
            title: '上传图片格式错误',
            desc: '上传图片格式只能为jpg, jpeg, png'
          });
        }
        if (!isLt2M) {
          this.$Notice.warning({
            title: '上传图片过大',
            desc: '上传图片大小不能超过2M'
          });
        }
        if (isJPG && isLt2M) this.formLoading = true;
        return isJPG && isLt2M;
      },
      // 上传成功
      handleAvatarSuccess (res, file) {
        this.formLoading = false;
        if (res.error === 'INTERNAL_EXCEPTION') {
          this.$Notice.info({title: '上传图片超时，请稍后再试!'});
          this.infoForm.avatar = '';
          return;
        }
        this.$Notice.success({title: '上传成功'});
        this.infoForm.avatar = res.data.ossKey;
      },
      // 发送验证码
      async sendSmsCode () {
        if (!this.phoneForm.phone) {
          this.$Notice.info({title: '请输入手机号'});
          return;
        }
        if (this.companyUserInfo.phone === this.phoneForm.phone) {
          this.$Notice.info({title: '手机号不能和原手机号相同！'});
          return;
        }
        if (!this.captcha) {
          this.$Notice.info({title: '请输入图片验证码'});
          return;
        }
        this.phoneFunLoading = true;
        this.companyUserInfo;
        await sendSmsCode({phone: this.phoneForm.phone}, {randKey: this.code, captcha: this.captcha}); // 获取短信验证码接口
        this.$Notice.success({title: '发送成功'});
        this.countDownIntervalid = setInterval(() => {
          if (this.countDown <= 0) {
            this.phoneFunLoading = false;
            this.countDown = 60;
            clearInterval(this.countDownIntervalid);
          } else {
            this.countDown = this.countDown - 1;
          }
        }, 1000);
      },
      // 确认修改手机
      changePhone (name) {
        this.$refs[name].validate((valid) => {
          if (!valid) return;
          this.$confirm('确定修改手机吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            let para = {phone: this.phoneForm.phone, smsCode: this.phoneForm.smsCode};
            this.formLoading = true;
            await changePhone(para);
            this.$Notice.success({title: '修改成功'});
          }).catch(() => {
            this.formLoading = false;
          });
        });
      }
    },
    beforeDestroy () {
      clearInterval(this.countDownIntervalid);
    }
  };
</script>
